
#include "inputpanelcontext.h"
#include "inputpanel.h"

InputPanelContext::InputPanelContext()
{
    inputPanel = new InputPanel;
    connect(inputPanel, SIGNAL(characterGenerated(QChar)), this, SLOT(sendChar(QChar))); //sendCharacter(QChar character)
}

InputPanelContext::~InputPanelContext()
{
    delete inputPanel;
}

bool InputPanelContext::filterEvent(const QEvent *event)
{
    if (event->type() == QEvent::RequestSoftwareInputPanel) {
            updatePosition();
            inputPanel->show();
            return true;
        } else if (event->type() == QEvent::CloseSoftwareInputPanel) {
            inputPanel->hide();
            return true;
        }
        return false;

}

QString InputPanelContext::identifierName()
{
    return "InputPanelContext";
}

void InputPanelContext::reset()
{

}

QString InputPanelContext::language()
{
    return "en_US";
}

bool InputPanelContext::isComposing() const
{
    return false;
}

void InputPanelContext::sendChar(QChar character) //sendCharacter(QChar character)
{
    QPointer<QWidget> w = focusWidget();

        if (!w)
            return;

        QKeyEvent keyPress(QEvent::KeyPress, character.unicode(), Qt::NoModifier, QString(character));
        QApplication::sendEvent(w, &keyPress);

        if (!w)
            return;

        QKeyEvent keyRelease(QEvent::KeyPress, character.unicode(), Qt::NoModifier, QString());
        QApplication::sendEvent(w, &keyRelease);
}

void InputPanelContext::updatePosition()
{
    QWidget *widget = focusWidget();
    if (!widget)
        return;

    QRect widgetRect = widget->rect();
    QPoint panelPos = QPoint(widgetRect.left(), widgetRect.bottom() + 2);
    panelPos = widget->mapToGlobal(panelPos);
    inputPanel->move(panelPos);
}
